<?php

/**
 * 定时消息推送
 *
 * @author huliren<huliren0516@163.com>
 */

define('SITE_AUTH', 'mobile-app-push-record');
require('../../../common.inc.php');

use \lib\core\AdminAction;
use  \Common\Bridge;

class pushrecord extends AdminAction
{
    /**
     * 首页
     */
    public function doDefault()
    {
        $page = (int)$_GET['page'];
        $status = trim($_GET['status']);

        $smarty = $this->app->page();
        if ($page < 1) {
            $page = 1;
        }
        $limit = 15;
        $offset = ($page - 1) * $limit;
        $where = 'Type=1';
        if ($status !== '') {
            $where .= ' AND Status = ' . $status;
        }

        $sql = "SELECT * FROM AdminCron WHERE $where ORDER BY CronId DESC LIMIT $offset,$limit";
        $sql_count = "SELECT count(CronId) AS num FROM AdminCron WHERE $where";
        $count = $this->readDb($sql_count);
        $count = (int)$count[0]['num'];

        if ($count > 0) {
            $pagination = $this->pagination($count, $limit, $page);

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $list = $this->readDb($sql);

            $smarty->value('pagination', $pagination);
            $smarty->value('page_info', $page_info);
            $smarty->value('page', $page);
            $smarty->value('list', $list);
        }

        $smarty->output();
    }

    /**
     * 删除入口
     */
    public function doDelete()
    {
        $id = intval($_GET['id']);
        if ($id < 1) {
            HDshowMsg('删除失败', ['type' => 'error', 'desc' => '参数非法！']);
        }

        $pdo_w = Bridge::pdo(Bridge::DB_ADMIN_W);
        $where = ['CronId' => $id, 'Status' => 0];
        if ($pdo_w->delete('AdminCron', $where)) {
            $this->adminLog('删除定时推送', $id, 'del', serialize($where));
            HDshowMsg('删除成功！');
        } else {
            HDshowMsg('删除失败', ['type' => 'error', 'desc' => '请稍后再试！']);
        }
    }


    private $pdo_r;

    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_ADMIN_R);
        }
        $obj = $pdo->query($sql);
        return $obj->fetchAll();
    }
}

$app->run();
